require 'rake'
require 'rake/tasklib'
require 'ftools'

module Rubicant::Tasks
  class CopyFiles < Rake::TaskLib

    attr_reader :name
    attr_accessor :target_dir, :base_dir, :file_globs, :excludes

    def initialize(name)
      @name = name
      yield self if block_given?
      define
    end

    def define
      fail "Target directory must be defined (:target_dir)" if @target_dir.nil?
      fail "Source files must be defined (:file_globs)" if @file_globs.nil?
      fail "Base directory must be defined (:base_dir)" if @base_dir.nil?
      @excludes = [] if @excludes.nil?

      mkdir @target_dir unless (File.exists?(@target_dir))

      files = FileList.new
      @file_globs.each do |glob|
        files.include("#{@base_dir}/#{glob}")
      end

      @excludes.each do |exclude|
        files.exclude(exclude)
      end

      puts "Files are #{files}"
      
      files.each do |filename|
        target_dir_suffix = get_target_dir_suffix(filename)
        targetName = File.join(@target_dir, target_dir_suffix)
        file targetName do
          if (File.directory?(filename))
            mkdir_p targetName
          else
            puts "copying from #{filename} to #{targetName}"
            cp filename, targetName
          end
        end
        task @name => targetName
      end
      self
    end

  end

  def get_target_dir_suffix(file)
    suffix = file[@base_dir.length..file.length-1]
    puts "FileName is #{file}"
    puts "Base dir is #{@base_dir}"
    puts "Suffix is #{suffix}"
    return suffix
  end
end